package com.autobet.services;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.autobet.dao.CommonDao;
import com.autobet.model.support.AutoResult;
import com.autobet.model.table.AutoHis;
import com.autobet.model.table.ResultHis;
import com.autobet.utils.BetUtils;
import com.autobet.utils.HttpUtils;
import com.autobet.utils.MapKeyComparator;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.tomcat.jni.BIOCallback;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by yangd on 2017-08-27.
 */
@Service
public class ResultService {

    private static final Logger log = LoggerFactory.getLogger(ResultService.class);
    private static String RESULT_DNS = "http://www.1680180.com";
    private List<String> infoList = Collections.synchronizedList(new ArrayList());
    private Map<String, Integer> retryMap = new HashMap();
    @Autowired
    private CommonDao commonDao;

    public ResultService() {
    }

    public AutoResult getCurrentResultRetry(int times) throws Exception {
        for(int i = 1; i <= times; ++i) {
            try {
                Thread.sleep((long)(2000 * i));
                AutoResult autoResult = this.getCurrentResult();
                if(autoResult != null) {
                    return autoResult;
                }

                log.info("抓不到开奖结果，重试..");
                this.addInfo("抓不到开奖结果，重试第" + i + "次..", "02");
            } catch (Exception var4) {
                if(i == times) {
                    throw var4;
                }

                log.info("抓不到开奖结果，重试..");
                this.addInfo("抓不到开奖结果，重试第" + i + "次..", "02");
            }
        }

        throw new Exception("重试" + times + "次抓取所有开奖结果失败！");
    }

    public AutoResult getCurrentResult() throws Exception {
        try {
            double d = (double)((long)(Math.random() * 1.0E9D * 1000.0D));
            String url = EnvConfigService.getQueryBetUrl() + "/member/lastResult?lottery=PK10JSC&_=" + d;
            Map<String, String> headerMap = new HashMap();
            headerMap.put("Cookie", EnvConfigService.getCookie());
            String postresult = HttpUtils.post(url, (Map)null, headerMap);
            JSONObject jsonobj = JSONObject.parseObject(postresult);
            AutoResult autoResult = new AutoResult();
            autoResult.setBuyResult(jsonobj.getString("result"));
            autoResult.setBuyResultArray(jsonobj.getString("result").split(","));
            autoResult.setBuydateId(jsonobj.getString("drawNumber"));
            return autoResult;
        } catch (Exception var8) {
            log.error("获取当前开奖结果失败！", var8);
            throw var8;
        }
    }

    /**
     * 获取所有开奖结果
     * @param times
     * @return
     * @throws Exception
     */
    public List<ResultHis> getCurrentAllResultRetry(int times) throws Exception {
        for(int i = 1; i <= times; ++i) {
            try {
                Thread.sleep((long)(2000 * i));
                List<ResultHis> list = this.getCurrentAllResult();
                if(list != null && list.size() != 0) {
                    return list;
                }

                log.info("抓不到所有开奖结果，重试..");
                this.addInfo("抓不到所有开奖结果，重试第" + i + "次..", "02");
            } catch (Exception var4) {
                if(i == times) {
                    throw var4;
                }

                log.info("抓不到所有开奖结果，重试..");
                this.addInfo("抓不到所有开奖结果，重试第" + i + "次..", "02");
            }
        }

        throw new Exception("重试" + times + "次抓取所有开奖结果失败！");
    }

    public List<ResultHis> getCurrentAllResultNew() throws Exception {
        try {
            String url = "http://api.1680180.com/lotteryBasePKS/getBasePKSList.do?date=&lottObj=";
            Map headerMap = new HashMap();
            headerMap.put("Host", "api.1680180.com");
            headerMap.put("Origin", "http://www.1680180.com");
            headerMap.put("Referer", "http://www.1680180.com/html/PK10/pk10kai_history.html");
            headerMap.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36");
            String postresult = HttpUtils.post(url, headerMap);
            JSONObject jsonobj = JSONObject.parseObject(postresult);
            JSONObject jsontmp = JSONObject.parseObject(jsonobj.getString("result"));
            String liststr = jsontmp.getString("data");
            JSONArray jsonArray = JSONObject.parseArray(liststr);
            List<ResultHis> list = new ArrayList();

            for(int i = 0; i < jsonArray.size(); ++i) {
                ResultHis resultHis = new ResultHis();
                JSONObject obj = (JSONObject)jsonArray.get(i);
                resultHis.setBuydateId(obj.getString("preDrawIssue"));
                resultHis.setResultTime(obj.getString("preDrawTime"));
                String[] result = obj.getString("preDrawCode").split(",");
                resultHis.setR1(BetUtils.formatResult(result[0]));
                resultHis.setR2(BetUtils.formatResult(result[1]));
                resultHis.setR3(BetUtils.formatResult(result[2]));
                resultHis.setR4(BetUtils.formatResult(result[3]));
                resultHis.setR5(BetUtils.formatResult(result[4]));
                resultHis.setR6(BetUtils.formatResult(result[5]));
                resultHis.setR7(BetUtils.formatResult(result[6]));
                resultHis.setR8(BetUtils.formatResult(result[7]));
                resultHis.setR9(BetUtils.formatResult(result[8]));
                resultHis.setR10(BetUtils.formatResult(result[9]));
                resultHis.setResultDate(obj.getString("preDrawTime").substring(0, 10).replaceAll("-", ""));
                if(resultHis.getResultTime().indexOf("09:06:") <= 0 && resultHis.getResultTime().indexOf("09:07:") <= 0) {
                    resultHis.setFirstFlag("n");
                } else {
                    resultHis.setFirstFlag("y");
                }

                list.add(resultHis);
            }

            log.info("###########################" + JSONObject.toJSONString(list));
            return list;
        } catch (Exception var13) {
            log.error("获取当天历史结果出错！", var13);
            throw var13;
        }
    }

    public List<ResultHis> getCurrentAllResult() throws Exception {
        try {
            String url = EnvConfigService.getQueryBetUrl() + "/member/dresult?lottery=PK10JSC";
            if( !"".equals(EnvConfigService.searchDate)){
                url += "&date=" + EnvConfigService.searchDate;
            }
            Map<String, String> headerMap = new HashMap();
            headerMap.put("Cookie", EnvConfigService.getCookie());
            String postresult = HttpUtils.post(url, headerMap);
            Document document = Jsoup.parse(postresult);
            Element date = document.getElementById("date");
            String strdate = date.val().replaceAll("-", "");
            Elements tables = document.getElementsByClass("table_ball");
            Element table = tables.first();
            Elements tbodys = table.getElementsByTag("tbody");
            Element tbody = tbodys.first();
            Elements trs = tbody.getElementsByTag("tr");
            List<ResultHis> list = new ArrayList();
            Iterator var13 = trs.iterator();

            while(var13.hasNext()) {
                Element tr = (Element)var13.next();
                Elements tds = tr.getElementsByTag("td");
                ResultHis resultHis = new ResultHis();
                resultHis.setResultDate(strdate);

                String firstArea = "";
                String secondArea = "";
                for(int i = 0; i < tds.size(); ++i) {
                    Element td = (Element)tds.get(i);
                    if(i == 0) {
                        resultHis.setBuydateId(td.html());
                    } else if(i == 1) {
                        resultHis.setResultTime(td.html());
                        if(resultHis.getResultTime().indexOf("07:30") <= 0 && resultHis.getResultTime().indexOf("07:30") <= 0) {
                            resultHis.setFirstFlag("n");
                        } else {
                            resultHis.setFirstFlag("y");
                        }
                    } else if(i == 2) {
                        resultHis.setR1(td.getElementsByTag("span").first().html());
                        firstArea += td.getElementsByTag("span").first().html()+",";
                    } else if(i == 3) {
                        resultHis.setR2(td.getElementsByTag("span").first().html());
                        firstArea += td.getElementsByTag("span").first().html()+",";
                    } else if(i == 4) {
                        resultHis.setR3(td.getElementsByTag("span").first().html());
                        firstArea += td.getElementsByTag("span").first().html()+",";
                    } else if(i == 5) {
                        resultHis.setR4(td.getElementsByTag("span").first().html());
                        firstArea += td.getElementsByTag("span").first().html()+",";
                    } else if(i == 6) {
                        resultHis.setR5(td.getElementsByTag("span").first().html());
                        firstArea += td.getElementsByTag("span").first().html()+",";
                    } else if(i == 7) {
                        resultHis.setR6(td.getElementsByTag("span").first().html());
                        secondArea += td.getElementsByTag("span").first().html()+",";
                    } else if(i == 8) {
                        resultHis.setR7(td.getElementsByTag("span").first().html());
                        secondArea += td.getElementsByTag("span").first().html()+",";
                    } else if(i == 9) {
                        resultHis.setR8(td.getElementsByTag("span").first().html());
                        secondArea += td.getElementsByTag("span").first().html()+",";
                    } else if(i == 10) {
                        resultHis.setR9(td.getElementsByTag("span").first().html());
                        secondArea += td.getElementsByTag("span").first().html()+",";
                    } else if(i == 11) {
                        resultHis.setR10(td.getElementsByTag("span").first().html());
                        secondArea += td.getElementsByTag("span").first().html()+",";
                    }
                }
                resultHis.setFirstArea(firstArea);
                resultHis.setSecondArea(secondArea);
                list.add(resultHis);
            }

            log.info("###########################" + JSONObject.toJSONString(list));
            return list;
        } catch (Exception var19) {
            log.error("获取当天历史结果出错！", var19);
            throw var19;
        }
    }

    public List<ResultHis> getCurrentAllResultOld() throws Exception {
        try {
            double d = Math.random() * 1.0D;
            String url = "http://www.1680180.com/Open/CurrentOpen?code=10016&_=" + d;
            String postresult = HttpUtils.post(url);
            JSONObject jsonobj = JSONObject.parseObject(postresult);
            String liststr = jsonobj.getString("list");
            JSONArray jsonArray = JSONObject.parseArray(liststr);
            List<ResultHis> list = new ArrayList();

            for(int i = 0; i < jsonArray.size(); ++i) {
                ResultHis resultHis = new ResultHis();
                JSONObject obj = (JSONObject)jsonArray.get(i);
                resultHis.setBuydateId(obj.getString("c_t"));
                resultHis.setResultTime(obj.getString("c_d"));
                String[] result = obj.getString("c_r").split(",");
                resultHis.setR1(result[0]);
                resultHis.setR2(result[1]);
                resultHis.setR3(result[2]);
                resultHis.setR4(result[3]);
                resultHis.setR5(result[4]);
                resultHis.setR6(result[5]);
                resultHis.setR7(result[6]);
                resultHis.setR8(result[7]);
                resultHis.setR9(result[8]);
                resultHis.setR10(result[9]);
                resultHis.setResultDate(BetUtils.getCurrDateYYYY() + resultHis.getResultTime().substring(0, 5).replaceAll("/", ""));
                if(resultHis.getResultTime().indexOf("09:06:00") > 0) {
                    resultHis.setFirstFlag("y");
                } else {
                    resultHis.setFirstFlag("n");
                }

                list.add(resultHis);
            }

            return list;
        } catch (Exception var13) {
            log.error("获取当天历史结果出错！", var13);
            throw var13;
        }
    }

    public String getPridDataRetry(int times) throws Exception {
        for(int i = 1; i <= times; ++i) {
            try {
                Thread.sleep((long)(2000 * i));
                String pridData = this.getPridData();
                if(pridData != null && pridData != "") {
                    return pridData;
                }

                log.info("抓不到下单信息，重试..");
                this.addInfo("抓不到下单信息，重试第" + i + "次..", "02");
            } catch (Exception var4) {
                if(i == times) {
                    throw var4;
                }

                log.info("抓不到下单信息，重试..");
                this.addInfo("抓不到下单信息，重试第" + i + "次..", "02");
            }
        }

        throw new Exception("重试" + times + "次抓取下单信息失败！");
    }

    public String getPridData() throws Exception {
        try {
            double d = (double)((long)(Math.random() * 1.0E9D * 1000.0D));
            String posturl = EnvConfigService.getQueryBetUrl() + "/member/period?lottery=PK10JSC&_=" + d;
            Map<String, String> headerMap = new HashMap();
            headerMap.put("Cookie", EnvConfigService.getCookie());
            String postresult = HttpUtils.post(posturl, (Map)null, headerMap);
            return postresult;
        } catch (Exception var6) {
            log.error("获取下单信息失败！", var6);
            throw var6;
        }
    }

    public String getRpt() throws Exception {
        try {
            String posturl = EnvConfigService.getQueryBetUrl() + "/member/history";
            Map<String, String> headerMap = new HashMap();
            headerMap.put("Cookie", EnvConfigService.getCookie());
            String postresult = HttpUtils.post(posturl, (Map)null, headerMap);
            return postresult;
        } catch (Exception var4) {
            throw var4;
        }
    }

    public BigDecimal[] getAccount() throws Exception {
        try {
            double d = (double)((long)(Math.random() * 1.0E9D * 1000.0D));
            String posturl = EnvConfigService.getQueryBetUrl() + "/member/accounts?_=" + d;
            Map<String, String> headerMap = new HashMap();
            headerMap.put("Cookie", EnvConfigService.getCookie());
            String postresult = HttpUtils.post(posturl, (Map)null, headerMap);
            JSONArray sa = JSON.parseArray(postresult);
            JSONObject s = (JSONObject)sa.get(0);
            BigDecimal[] account = new BigDecimal[]{s.getBigDecimal("balance"), s.getBigDecimal("maxLimit")};
            return account;
        } catch (Exception var9) {
            BigDecimal[] account = new BigDecimal[]{new BigDecimal("-1"), new BigDecimal("-1")};
            return account;
        }
    }

    public void setAccountRpt() throws Exception {
        try {
//            String posturl = "http://120.26.231.223:8989/rpt";
//            Map jsonMap = new HashMap();
//            jsonMap.put("accountId", EnvConfigService.getAccountId());
//            InetAddress ia = null;
//            ia = InetAddress.getLocalHost();
//            String localip = ia.getHostAddress();
//            jsonMap.put("clientIp", localip);
//            jsonMap.put("remark", EnvConfigService.getTaskStatus());
//            jsonMap.put("rpt", Base64.getEncoder().encodeToString(this.getRpt().getBytes()));
//            Map<String, String> paramap = new HashMap();
//            paramap.put("rptInfo", JSONObject.toJSONString(jsonMap));
//            String postresult = HttpUtils.post(posturl, paramap, (Map)null);
//            log.info("报告完毕.." + postresult);
        } catch (Exception var7) {
            log.info("报告异常");
        }
    }

    public void getMgr() throws Exception {
        try {
//            String posturl = "http://120.26.231.223:8989/mgr";
//            Map jsonMap = new HashMap();
//            jsonMap.put("accountId", EnvConfigService.getAccountId());
//            BigDecimal betAmount = this.commonDao.queryRealAutoHisBuymoneytakeByResultDate(BetUtils.getCurrDateYYYYMMDD(), "both");
//            jsonMap.put("betAmount", betAmount.toString());
//            jsonMap.put("betDate", BetUtils.getCurrDateYYYYMMDD());
//            InetAddress ia = null;
//            ia = InetAddress.getLocalHost();
//            String localip = ia.getHostAddress();
//            jsonMap.put("clientIp", localip);
//            jsonMap.put("remark", EnvConfigService.getTaskStatus());
//            jsonMap.put("accountAmount", this.getAccount()[0].toString());
//            jsonMap.put("accountPreAmount", this.getAccount()[1].toString());
//            Map<String, String> paramap = new HashMap();
//            paramap.put("mgrinfo", JSONObject.toJSONString(jsonMap));
//            String postresult = HttpUtils.post(posturl, paramap, (Map)null);
//            JSONObject jsonobj = JSONObject.parseObject(postresult);
//            if("success".equals(jsonobj.getString("status"))) {
//                EnvConfigService.setTaskStatus("STOP");
//            }

        } catch (Exception var9) {
            log.info("异常");
        }
    }

    public AutoResult getLastResult() throws Exception {
        try {
            double d = (double)((long)(Math.random() * 1.0E9D * 1000.0D));
            String posturl = EnvConfigService.getQueryBetUrl() + "/member/lastResult?lottery=PK10JSC&_=" + d;
            Map<String, String> headerMap = new HashMap();
            headerMap.put("Cookie", EnvConfigService.getCookie());
            String postresult = HttpUtils.post(posturl, (Map)null, headerMap);
            JSONObject jsonObject = JSONObject.parseObject(postresult);
            AutoResult autoResult = new AutoResult();
            autoResult.setBuydateId(jsonObject.getString("drawNumber"));
            autoResult.setBuyResult(jsonObject.getString("result"));
            autoResult.setBuyResultArray(jsonObject.getString("result").split(","));
            log.info("查询上一期结果成功，期数：{}，开奖结果{}", autoResult.getBuydateId(), autoResult.getBuyResult());
            return autoResult;
        } catch (Exception var8) {
            log.error("获取上期结果失败！", var8);
            throw new Exception("获取上期投注结果失败！");
        }
    }

    public String getResultServerTime() throws Exception {
        try {
            double d = Math.random() * 1.0D;
            String posturl = "http://www.1680180.com/Open/ServerTime?_=" + d;
            String postresult = HttpUtils.post(posturl);
            JSONObject jsonobj = JSONObject.parseObject(postresult);
            String servertime = jsonobj.getString("d");
            servertime = servertime.split(" ")[1].replaceAll(":", "");
            return servertime;
        } catch (Exception var7) {
            log.error("获取开奖服务器时间失败！", var7);
            throw var7;
        }
    }

    public List<String> querySaveAutoHis(String betType) throws Exception {
        try {
            List<String> retrunList = new ArrayList();
            StringBuffer returnBuffer = new StringBuffer();
            List<AutoHis> list = this.commonDao.queryAutoHisTop(betType);
            if(list != null && list.size() != 0) {
                Map<String, List<AutoHis>> buydateIdMap = new HashMap();
                Iterator var6 = list.iterator();

                while(var6.hasNext()) {
                    AutoHis autoHis = (AutoHis)var6.next();
                    List<AutoHis> buydataIdList = (List)buydateIdMap.get(autoHis.getBuydateId());
                    if(buydataIdList == null) {
                        buydataIdList = new ArrayList();
                        buydataIdList.add(autoHis);
                        buydateIdMap.put(autoHis.getBuydateId(), buydataIdList);
                    } else {
                        buydataIdList.add(autoHis);
                    }
                }

                Map<String, List<AutoHis>> sortBuydateIdMap = MapKeyComparator.sortMapByKey(buydateIdMap, 1);
                Iterator itBuydateId = sortBuydateIdMap.keySet().iterator();

                while(itBuydateId.hasNext()) {
                    String buydateId = (String)itBuydateId.next();
                    List<AutoHis> buydateidDetailList = (List)sortBuydateIdMap.get(buydateId);
                    Map<String, String> singleAutoHisMap = new HashMap();

                    AutoHis autoHis;
                    String buyWaht;
                    String showStr;
                    for(Iterator var11 = buydateidDetailList.iterator(); var11.hasNext(); singleAutoHisMap.put(autoHis.getBuyNum(), showStr)) {
                        autoHis = (AutoHis)var11.next();
                        String buyNum = "[" + autoHis.getBuyNum() + "]";
                        buyWaht = "";
                        String buyResult = "";
                        if("dx".equals(autoHis.getBuyType())) {
                            if("D".equals(autoHis.getBuyWhat())) {
                                buyWaht = "大";
                            } else {
                                buyWaht = "小";
                            }

                            if("01".equals(autoHis.getBuyResult())) {
                                buyResult = "<span style='background-color:red;'>赢</span>";
                            } else if("02".equals(autoHis.getBuyResult())) {
                                if(!"15".equals(autoHis.getBetRule()) && !"25".equals(autoHis.getBetRule())) {
                                    buyResult = "<span style='background-color:green;'>输</span>";
                                } else {
                                    buyResult = "<span style='background-color:yellow;'>输</span>";
                                }
                            } else {
                                buyResult = "待";
                            }
                        } else {
                            if("S".equals(autoHis.getBuyWhat())) {
                                buyWaht = "双";
                            } else {
                                buyWaht = "单";
                            }

                            if("01".equals(autoHis.getBuyResult())) {
                                buyResult = "<span style='background-color:red;'>赢</span>";
                            } else if("02".equals(autoHis.getBuyResult())) {
                                if(!"15".equals(autoHis.getBetRule()) && !"25".equals(autoHis.getBetRule())) {
                                    buyResult = "<span style='background-color:green;'>输</span>";
                                } else {
                                    buyResult = "<span style='background-color:yellow;'>输</span>";
                                }
                            } else {
                                buyResult = "待";
                            }
                        }

                        String buyAmount = autoHis.getBuyAmount().toString();
                        if(autoHis.getBuyAmount().intValue() < 10) {
                            buyAmount = "__" + buyAmount;
                        } else if(9 < autoHis.getBuyAmount().intValue() && autoHis.getBuyAmount().intValue() < 100) {
                            buyAmount = "_" + buyAmount;
                        }

                        String currBuyresult = autoHis.getCurrBuyresult();
                        showStr = buyWaht + "" + buyAmount + " " + buyResult;
                        if("y".equals(autoHis.getFirstFlag())) {
                            showStr = "<span style='background-color:gray;'>" + showStr + "</span>";
                        }
                    }

                    Map<String, String> sortMap = MapKeyComparator.sortMapByKey(singleAutoHisMap, 0);
                    Iterator<String> it = sortMap.keySet().iterator();
                    StringBuffer result = new StringBuffer();
                    result.append("").append(buydateId).append("").append("");

                    while(it.hasNext()) {
                        buyWaht = (String)it.next();
                        result.append("<span style='font-weight:bold;font-size:150%;'>[").append(buyWaht).append("]</span>").append((String)sortMap.get(buyWaht));
                    }

                    returnBuffer.append(result.toString()).append("\r\n");
                    retrunList.add(result.toString());
                }

                return retrunList;
            } else {
                return null;
            }
        } catch (Exception var19) {
            log.error("查询投注结果失败！", var19);
            throw var19;
        }
    }

    public void resultHis() throws Exception {
        try {
            this.commonDao.saveOrUpdateResultHis(this.getCurrentAllResult());
        } catch (Exception var2) {
            log.error("保存当日历史开奖记录失败", var2);
            throw var2;
        }
    }

    public void addInfo(String info, String type) {
        if("01".equals(type)) {
            this.getInfoList().add("<span style='background-color:red;'>" + BetUtils.getCurrDate() + ":" + info + "</span>");
        }

        if("02".equals(type)) {
            this.getInfoList().add("<span style='background-color:yellow;'>" + BetUtils.getCurrDate() + ":" + info + "</span>");
        } else {
            this.getInfoList().add(BetUtils.getCurrDate() + ":" + info);
        }

    }

    public void addInfo(String info) {
        this.getInfoList().add(BetUtils.getCurrDate() + ":" + info);
    }

    public List<String> getInfoList() {
        return this.infoList;
    }

    /**
     * 统计盈亏
     */
    public void sumTakeMomey() {

        try {
            List<AutoHis> autoHisList = this.commonDao.querySumTakeMoneyAutoHis();

            for( int i = 0 ; i < autoHisList.size() ; i++){

                String type =  autoHisList.get(i).getBuyType();
                String num =  autoHisList.get(i).getBuyNum();
                String id =  autoHisList.get(i).getBuydateId();

                BigDecimal sum = this.commonDao.queryAutoHisBuymoneytakeSum( type , num , id );

                this.commonDao.setTakeMoneySum( sum , type , num , id );
            }
        } catch (Exception e) {
            log.error("统计开奖盈亏失败", e);
            e.printStackTrace();
        }

    }

    /**
     * 计算符合规则数字
     */
    public boolean buildSelect(ResultHis resultHis){
        String firstSelect = "";
        String secondSelect = "";
        try {
            /*查询计算的期数*/
            String buydateId2 = String.valueOf(Integer.parseInt(resultHis.getBuydateId()) - Integer.parseInt(EnvConfigService.selectPeriod) + 1 );

            addInfo("统计" + resultHis.getBuydateId() + "期到" + buydateId2 +"期");
            List<ResultHis> resultHisList = this.commonDao.queryResultHisBySelectPeriod(resultHis.getBuydateId(), buydateId2);
            if( resultHis.getBuydateId().equals("30542349")){
                log.error("30542349");
            }
            /*判断是否查到数据*/

            if(resultHisList!=null ){
                /*判断是否有足够的期数*/
                if(resultHisList.size() == Integer.parseInt(EnvConfigService.selectPeriod)){

                    for(int i = 1 ; i <= 10 ; i++){
                        List<ResultHis> firstSelectList = this.commonDao.queryResultHisBySelectFirst(resultHis.getBuydateId(),buydateId2,String.valueOf(i)+",");
                        List<ResultHis> secondSelectList = this.commonDao.queryResultHisBySelectSecond(resultHis.getBuydateId(),buydateId2,String.valueOf(i)+",");
                        if(firstSelectList == null || secondSelectList ==null){
                            log.error("计算投注信息失败");
                            return false;
                        }

                        if(firstSelectList.size() ==  Integer.parseInt(EnvConfigService.selectPeriod)){
                            firstSelect +=String.valueOf(i)+",";
                        }

                        if(secondSelectList.size() ==  Integer.parseInt(EnvConfigService.selectPeriod)){
                            secondSelect +=String.valueOf(i)+",";
                        }
                    }

                }else{
                    firstSelect = "不满足计算条件";
                    secondSelect = "不满足计算条件";
                }

                if(firstSelect.equals("")){
                    resultHis.setFirstSelect(" ");
                }else{
                    resultHis.setFirstSelect(firstSelect);
                }

                if(secondSelect.equals("")){
                    resultHis.setSecondSelect(" ");
                }else{
                    resultHis.setSecondSelect(secondSelect);
                }

                this.commonDao.updateResultHisByBuydateId(resultHis);

            }else{
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("计算投注信息失败", e);
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 查询投注数据
     * @return
     * @throws Exception
     */
    public List<String> queryResultHis() throws Exception {
        try {
            List<String> retrunList = new ArrayList();
            /*获取结果*/
            List<ResultHis> list = this.commonDao.queryResultHis();
            if(list != null && list.size() != 0) {

                for(int i = 0; i<list.size();i++){
                    StringBuffer result = new StringBuffer();
                    ResultHis resultHis = list.get(i);
                    ResultHis resultHisNext =new ResultHis();
                    boolean toDoFlag = true;
                    if(i!=0){
                        resultHisNext = list.get(i-1);
                    }else{
                        toDoFlag = false;
                    }

                    result.append("<div class='div-inline buydateId div28'>").append(resultHis.getBuydateId()).append("</div>").append("");
                    result.append("<div class='div-inline str div28'>").append("&nbsp;&nbsp;&nbsp;&nbsp;[第一组").append("").append("：</div>");
                    result.append("<div class='div-inline'><div class='ballOut " + getBallCss(resultHis.getR1()) +" "+getBallChangeCss(resultHis.getR1(),resultHis,resultHisNext,toDoFlag)+"'> <span class='ballIn'>" + resultHis.getR1() + "</span></div><div class= "+getBallCursor(0,list,i)+"></div></div>");
                    result.append("<div class='div-inline'><div class='ballOut " + getBallCss(resultHis.getR2()) +" "+getBallChangeCss(resultHis.getR2(),resultHis,resultHisNext,toDoFlag)+"'> <span class='ballIn'>" + resultHis.getR2() + "</span></div><div class= "+getBallCursor(1,list,i)+"></div></div>");
                    result.append("<div class='div-inline'><div class='ballOut " + getBallCss(resultHis.getR3()) +" "+getBallChangeCss(resultHis.getR3(),resultHis,resultHisNext,toDoFlag)+"'> <span class='ballIn'>" + resultHis.getR3() + "</span></div><div class= "+getBallCursor(2,list,i)+"></div></div>");
                    result.append("<div class='div-inline'><div class='ballOut " + getBallCss(resultHis.getR4()) +" "+getBallChangeCss(resultHis.getR4(),resultHis,resultHisNext,toDoFlag)+"'> <span class='ballIn'>" + resultHis.getR4() + "</span></div><div class= "+getBallCursor(3,list,i)+"></div></div>");
                    result.append("<div class='div-inline'><div class='ballOut " + getBallCss(resultHis.getR5()) +" "+getBallChangeCss(resultHis.getR5(),resultHis,resultHisNext,toDoFlag)+"'> <span class='ballIn'>" + resultHis.getR5() + "</span></div><div class= "+getBallCursor(4,list,i)+"></div></div>");
//                    result.append("<div class='div-inline div28' style='width:100px;'>【 <span class='buydateId' >"+resultHis.getFirstSelect()+"</span>】</div>");

                    result.append("<div class='div-inline'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>");

                    result.append("<div class='div-inline str div28'>").append("第二组").append("").append("：</div>");
                    result.append("<div class='div-inline'><div class='ballOut " + getBallCss(resultHis.getR6()) +" "+getBallChangeCss(resultHis.getR6(),resultHis,resultHisNext,toDoFlag)+"'> <span class='ballIn'>" + resultHis.getR6() + "</span></div><div class= "+getBallCursor(5,list,i)+"></div></div>");
                    result.append("<div class='div-inline'><div class='ballOut " + getBallCss(resultHis.getR7()) + " "+getBallChangeCss(resultHis.getR7(),resultHis,resultHisNext,toDoFlag)+"'> <span class='ballIn'>" + resultHis.getR7() + "</span></div><div class= "+getBallCursor(6,list,i)+"></div></div>");
                    result.append("<div class='div-inline'><div class='ballOut " + getBallCss(resultHis.getR8()) + " "+getBallChangeCss(resultHis.getR8(),resultHis,resultHisNext,toDoFlag)+"'> <span class='ballIn'>" + resultHis.getR8() + "</span></div><div class= "+getBallCursor(7,list,i)+"></div></div>");
                    result.append("<div class='div-inline'><div class='ballOut " + getBallCss(resultHis.getR9()) + " "+getBallChangeCss(resultHis.getR9(),resultHis,resultHisNext,toDoFlag)+"'> <span class='ballIn'>" + resultHis.getR9() + "</span></div><div class= "+getBallCursor(8,list,i)+"></div></div>");
                    result.append("<div class='div-inline'><div class='ballOut " + getBallCss(resultHis.getR10()) + " "+getBallChangeCss(resultHis.getR10(),resultHis,resultHisNext,toDoFlag)+"'> <span class='ballIn'>" + resultHis.getR10() + "</span></div><div class= "+getBallCursor(9,list,i)+"></div></div>");
//                    result.append("<div class='div-inline div28' >【<span class='buydateId' >"+resultHis.getSecondSelect()+"</span>】");
                    result.append("]</div>");
                    retrunList.add(result.toString());
                }


                return retrunList;
            } else {
                return null;
            }
        } catch (Exception var19) {
            log.error("查询投注结果失败！", var19);
            throw var19;
        }
    }

    /**
     * 判断球颜色
     * @param num
     * @return
     */
    private static String getBallCss(String num){
        String ballCss ="b1";
        if(num.equals("1")){
            ballCss = "b1";
        }
        if(num.equals("2")){
            ballCss = "b2";
        }
        if(num.equals("3")){
            ballCss = "b3";
        }
        if(num.equals("4")){
            ballCss = "b4";
        }
        if(num.equals("5")){
            ballCss = "b5";
        }
        if(num.equals("6")){
            ballCss = "b6";
        }
        if(num.equals("7")){
            ballCss = "b7";
        }
        if(num.equals("8")){
            ballCss = "b8";
        }
        if(num.equals("9")){
            ballCss = "b9";
        }
        if(num.equals("10")){
            ballCss = "b10";
        }

        return ballCss;
    }

    /**
     * 判断球背景颜色
     * @param num
     * @param resultHis
     * @param resultHisNext
     * @return
     */
    private static String getBallChangeCss(String num,ResultHis resultHis,ResultHis resultHisNext,boolean toDoFlag){
        String ballCss ="newBall";
        try{

            if(toDoFlag){
                String result = resultHis.getFirstArea() + resultHis.getSecondArea();
                String resultNext = resultHisNext.getFirstArea() + resultHisNext.getSecondArea();
                String[] resultList = result.split(",");
                String[] resultNextList = resultNext.split(",");
                int resultIndex = 0;
                int resultNextIndex = 0;
                for(int i=0;i< resultList.length;i++){
                    if( num.equals(resultList[i])){
                        resultIndex=i;
                        break;
                    }
                }

                for(int i=0;i< resultNextList.length;i++){
                    if( num.equals(resultNextList[i])){
                        resultNextIndex=i;
                        break;
                    }
                }

                if( (resultIndex <=4 && resultNextIndex<=4) ||  (resultIndex >=5 && resultNextIndex>=5)){
                    ballCss ="ballNoChange";
                }else{
                    ballCss ="ballChange";
                }
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        return ballCss;
    }

    /**
     * 获取光标样式
     * @param no
     * @param list
     * @param index
     * @return
     */
    private static String getBallCursor (int no,List<ResultHis> list,int index){
        String ballCursor = "nocursor";
        StringBuilder color = new StringBuilder();
        String aa =  list.get(index).getBuydateId();
        if(aa.equals("30662673")  ){
            aa =list.get(index).getBuydateId();
        }
        if(index < list.size() && index > 0){
            String result = list.get(index).getFirstArea() + list.get(index).getSecondArea();
            String resultNext = list.get(index-1).getFirstArea() + list.get(index-1).getSecondArea();
            String[] resultList = result.split(",");
            String[] resultNextList = resultNext.split(",");

            if(resultList[no].equals(resultNextList[no])){
                ballCursor = "cursor";
            }
        }
//        int start = index -1;
//
//        if(index >=1){
//            for(int i = start ; i<= index + 5    ;i++){
//                if(i <= 0 || i >= list.size() -5){
//                    continue;
//                }
//
//                ResultHis resultHis =list.get(i);
//                String result = resultHis.getFirstArea() + resultHis.getSecondArea();
//                String[] resultList = result.split(",");
////                log.info(resultHis.getBuydateId()+"{"+String.valueOf(i)+"}{"+String.valueOf(i-1)+"}{"+no+"}{"+resultList.length+"}{"+result+"}");
//                String ballCss = getBallChangeCss(resultList[no],resultHis,list.get(i-1),true);
//                if("newBall".equals(ballCss)){
//                    color.append("B");
//                }else if("ballNoChange".equals(ballCss)){
//                    color.append("R");
//                }else{
//                    color.append("G");
//                }
//            }
//        }
//
////        log.info(color.toString());
////        if(color.length() == 6){
////            if(color.toString().indexOf("GRGRGG") == 0  || color.toString().indexOf("RGRGRR") == 0){
////                ballCursor = "cursorblue";
////            }
////        }
//
//        if(color.length() == 7){
//            if(color.toString().indexOf("GRGRGG") == 0  || color.toString().indexOf("RGRGRR") == 0){
//                ballCursor = "cursorblue";
//            }
//            if(color.toString().indexOf("RGRGRGG") == 0  || color.toString().indexOf("GRGRGRR") == 0 ){
//                ballCursor = "cursor";
//            }
////        if(color.toString().contains("GGRGRGG") || color.toString().contains("RRGRGRR")){
////            ballCursor = "cursorbox";
////        }
//        }



        return ballCursor;
    }
}
